package com.lipaluma.example.clients.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lipaluma.example.clients.dao.IAccountDAO;
import com.lipaluma.example.clients.dao.IOrderDAO;
import com.lipaluma.example.clients.model.LineOrder;
import com.lipaluma.example.clients.model.Order;
import com.lipaluma.example.clients.model.Order.StatusEnum;

@Service
@Transactional
public class OrderService {

	@Autowired
	private IOrderDAO orderDAO;

	@Autowired
	private IAccountDAO accountDAO;

	public Order createNewOrder(Long idAccount, List<LineOrder> lines) {
		Order order = new Order();
		order.setAccount(accountDAO.findOne(idAccount));
		order.setLines(lines);
		order.setStatus(StatusEnum.CREATED);
		double totalAmount = 0.0;
		for (LineOrder line : lines) {
			totalAmount += line.getTotalAmount();
			line.setOrder(order);
		}
		order.setTotalAmount(totalAmount);
		orderDAO.save(order);
		return order;
	}
}
